package com.jwgf.common;

import android.os.Looper;
import android.os.SystemClock;
import android.util.Log;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;

import androidx.fragment.app.FragmentActivity;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableSource;
import io.reactivex.rxjava3.functions.Consumer;
import io.reactivex.rxjava3.functions.Function;
import io.reactivex.rxjava3.schedulers.Schedulers;

public class    ViewCache {
    private static ViewCache instance = new ViewCache();
    private SparseArray<View> views;

    private ViewGroup viewGroup;

    private final ExecutorService service;

    private ViewCache() {
        service = Executors.newSingleThreadExecutor();
        views = new SparseArray<>();
    }

    public static ViewCache getInstance() {
        return instance;
    }

    private void putView(int id, View v) {
        views.append(id, v);
    }

    public View getView(int id) {
        View v = views.get(id);
        views.remove(id);
        return v;

    }

    public Observable generateViews(FragmentActivity activity, List<Integer> layoutIdList) {
        viewGroup = new RelativeLayout(activity);

        return Observable.fromIterable(layoutIdList)
                .subscribeOn(Schedulers.io())
                .flatMap(new Function<Integer, ObservableSource<Integer>>() {
                    @Override
                    public ObservableSource<Integer> apply(Integer integer) throws Throwable {
                        return Observable.just(integer);
                    }
                })
                .doOnNext(new Consumer<Integer>() {
                    @Override
                    public void accept(Integer integer) throws Throwable {
                        if (Looper.myLooper() == null) {
                            Looper.prepare();
                        }
                        LayoutInflater inflater = LayoutInflater.from(activity);
                        long startTime = SystemClock.uptimeMillis();
                        View view = inflater.inflate(integer.intValue(), viewGroup, false);
                        long endTime = SystemClock.uptimeMillis() - startTime;
                        putView(integer, view);
                        Log.i("ViewCache", "push finished, inflate time=" + endTime + " size=" + views.size());

                    }
                })
                .observeOn(AndroidSchedulers.mainThread());

    }


}
